import Taro from "@tarojs/taro";
import { Notify } from "@taroify/core";
import {
  setBusinessInfo,
  setCommodityId,
  setHomeShow,
} from "@/store/reducers/businessInfo";
import store from "@/store/index";

import { setShopInfo, setUserInfo } from "@/store/reducers/userInfo";

const baseOptions = (params, method) => {
  const token = Taro.getStorageSync("token");
  const { url, data } = params;
  const contentType = params.contentType || "application/json";

  return new Promise((resolve, reject) => {
    let options = {
      url: process.env.TARO_APP_API + "/" + url,
      data,
      method: method,
      header: {
        "content-type": contentType,
      },
      success(res) {
        if (!res.data.code) {
          resolve(res.data);
          return;
        }
        if (res.data.code === 200) {
          resolve(res.data.data || res.data.msg);
        } else {
          if (res.data.code === 401) {
            Notify.open({
              type: "danger",
              message: "用户登录失效，请重新登录",
            });
            store.dispatch(setBusinessInfo({ id: "", info: {} }));
            store.dispatch(setHomeShow(false));
            store.dispatch(setCommodityId(""));
            store.dispatch(setUserInfo({}));
            store.dispatch(setShopInfo({}));
            Taro.removeStorageSync("token");
            Taro.removeStorageSync("userInfo");
          } else {
            Notify.open({ type: "danger", message: res.data.msg });
          }
          reject(res.data);
        }
      },
      fail(err) {
        console.log(err);
        reject(err);
      },
    };
    if (token) {
      options["header"]["Authorization"] = token;
    }
    Taro.request(options);
  });
};

export function requestGET(url, data = {}) {
  return baseOptions({ url, data }, "GET");
}

export function requestPOST(url, data = {}) {
  return baseOptions({ url, data }, "POST");
}

export function requestPUT(url, data = {}) {
  return baseOptions({ url, data }, "PUT");
}
